package com.cheche.dn.domain.admin;

import com.cheche.dn.common.base.IdEntity;
import com.cheche.dn.domain.Apis;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.Sets;

import javax.persistence.*;
import java.util.Set;

/**
 * Entity - Authority
 * Created by cheshun on 15/8/22.
 */
@Entity
@Table(name = "authority")
public class Authority extends IdEntity implements Apis {
    private static final long serialVersionUID = -486996966763435810L;

    public static final String NAME_PROPERTY_NAME = "name";

    public Authority() {
    }

    public Authority(Mapping mapping, String description) {
        this.url = mapping.getUrl();
        this.method = mapping.getMethod().name();
        this.name = buildName(url, method);
        this.description = description;
    }

    public Authority(String url, String method, String description) {
        this.url = url;
        this.method = method;
        this.name = buildName(url, method);
        this.description = description;
    }

    private String buildName(String url, String method) {
        url = url.replace("/", "_").replace("{", "").replace("}", "");
        if (method == null || method.equals("")) {
            return String.format("ROLE_%s", url.toUpperCase());
        }
        return String.format("ROLE_%s_%s", url.toUpperCase(), method.toUpperCase());
    }

    private String url;             // 权限控制URL
    private String method;          // Http Method
    private String name;            // 权限名字
    private String description;     // 权限描述

    private Set<Role> roles = Sets.newHashSet();

    @JsonProperty
    @Column(length = 50, nullable = false)
    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    @JsonProperty
    @Column(length = 10)
    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    @JsonProperty
    @Column(length = 50, nullable = false, unique = true)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @JsonProperty
    @Column(length = 100, nullable = false)
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @ManyToMany(mappedBy = "authorities", fetch = FetchType.LAZY)
    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

}
